<?php defined('SYSPATH') OR die('No direct script access.');
/**
 * 微信oAuth认证示例
 */
class Model_WechatOAuth2 extends Model {
	private $wechat;

	/**
	 * @var   string     default driver to use
	 */
	public static $default = 'default';

	/**
	 * @var   Kohana_Cache instances
	 */
	public static $instances = array();

	public static function instance($group = NULL)
	{
		// If there is no group supplied
		if ($group === NULL)
		{
			// Use the default setting
			$group = Model_WechatOAuth2::$default;
		}

		if (isset(Model_WechatOAuth2::$instances[$group]))
		{
			// Return the current group if initiated already
			return Model_WechatOAuth2::$instances[$group];
		}

		$config = Kohana::$config->load('wechat');

		if ( ! $config->offsetExists($group))
		{
			throw new Cache_Exception(
				'Failed to load Kohana Wechat group: :group',
				array(':group' => $group)
			);
		}

		// Create a new cache type instance
		Model_WechatOAuth2::$instances[$group] = new Model_WechatOAuth2($config[$group]);

		// Return the instance
		return Model_WechatOAuth2::$instances[$group];
	}

	public function __construct($options)
	{
		parent::__construct();
		$this->wechat = new Model_Wechat($options);
	}

	public function oauth()
	{
		$json = $this->wechat->getOauthAccessToken();

		return empty($json) ? FALSE : $json;
	}

	public function refresh($refresh_token)
	{
		return $this->wechat->getOauthRefreshToken($refresh_token);
	}

	public function redirect($url, $scope = 'snsapi_base')
	{
		$oauth_url = $this->wechat->getOauthRedirect($url, "wxbase", $scope);
		return HTTP::redirect($oauth_url);
	}

	public function get_user($access_token, $openid)
	{
		return $this->wechat->getOauthUserinfo($access_token, $openid);
	}
}